package com.ruoyi.order.utils;

import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@Component
public class VerifyCodeGen {

    /**
     * 生成订单商品核销码
     *
     * @return
     */

    private static final String CHAR_SET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final int RANDOM_PART_LENGTH = 4; // 可根据需要调整随机部分的长度

    /**
     * 生成订单商品核销码
     *
     * @return 包含英文和数字的核销码
     */
    public static String genVerifyCode() {
        String year = new SimpleDateFormat("yy").format(new Date());
        String day = String.format("%tj", new Date());
        String randomPart = generateRandomString(RANDOM_PART_LENGTH);
        String verifyCode = year + day + randomPart;
        return verifyCode;
    }

    /**
     * 生成指定长度的随机字符串，包含英文大写字母和数字
     *
     * @param length 随机字符串的长度
     * @return 随机字符串
     */
    private static String generateRandomString(int length) {
        Random random = new Random();
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(CHAR_SET.length());
            sb.append(CHAR_SET.charAt(index));
        }
        return sb.toString();
    }
}
